<template>
  <Card class="pt-[40px] px-[26px] rounded-tr-[0] rounded-tl-[0]">
    <div class="steps">
      <div v-for="item in steps" :key="item.label" class="item-box">
        <div class="item">
          <div class="view">
            <svg-icon v-if="stepsActive == item.value" icon-class="radio_selected" class="mx-[-3px] text-[24px] text-[#3487FF]" />
            <svg-icon v-if="stepsActive > item.value" icon-class="state_finish" class="mx-[-3px] text-[24px] text-[#3487FF]" />
            <svg-icon v-if="stepsActive < item.value" icon-class="state_finish_line" class="mx-[-3px] text-[24px] text-[var(--base-table-hover-bg-color)]" />

            <div class="link" :class="stepsActive > item.value ? 'atv' : ''" v-if="item.value != 9">
              <div v-if="stepsActive > item.value">
                <div v-for="i in 3" :key="i" class="dk-iconfont icon-ArrowRight dk-icon text-[var(--base-color)]"></div>
              </div>
            </div>
          </div>
          <div class="label" :class="stepsActive >= item.value ? 'text-[#3487FF]' : ''">{{ item.label }}</div>
        </div>
      </div>
    </div>

    <div class="pt-[24px]">
      <el-button color="#FF0000" type="danger" @click="gotoRefundRecord" v-if="isPermission([userAuthList.list.refund])">申请退款</el-button>
      <el-button color="#6C7283" type="primary" @click="gotoRefundReturn" v-if="isPermission([userAuthList.list.return])">申请退换货</el-button>
      <el-button type="primary" @click="handleEdit" v-if="isPermission([userAuthList.list.edit])"> 编辑订单 </el-button>
    </div>
  </Card>

  <div class="flex mt-[8px]" id="anchors">
    <div class="flex-1">
      <Card title="基础信息" class="pb-[4px] v-anchor">
        <div class="flex flex-wrap">
          <Descriptions
            v-for="item in baseInfo"
            :label="item.label"
            :key="item.label"
            :light="item.light"
            :value="formModel['base'][item.field] || '-'"
            :show="item.checkShow && Boolean(!formModel['base'][item.field]) ? false : undefined"
          />
        </div>
      </Card>

      <Card title="物流信息" class="pb-[4px] v-anchor">
        <div class="flex flex-wrap">
          <template v-for="item in logisticsInfo" :key="item.label">
            <Descriptions
              :label="item.label"
              :value="formModel['logistics'][item.field] || '-'"
              labelWidth="130px"
              v-if="!item.isFba || (item.isFba && formModel?.base?.shipping_type == 1)"
              :class="item.onClick ? 'link' : ''"
              :onclick="item.onClick"
            >
              <template #value>
                <span>
                  {{ item.unit ? item.unit : "" }}
                </span>
              </template>
            </Descriptions>
          </template>
        </div>
      </Card>
      <Card title="支付信息" class="pb-[4px] v-anchor">
        <div class="flex flex-wrap">
          <Descriptions v-for="item in paymentInfo" :label="item.label" :key="item.label" :value="formModel.base[item.field] || '-'">
            <template #value>
              {{ item.currency ? ` ${formModel.base.original_order_currency}` : "" }}
            </template>
          </Descriptions>
        </div>
      </Card>

      <Card title="商品信息" class="v-anchor">
        <template #right>
          <div class="flex items-center text-[14px] whitespace-nowrap ml-[32px] leading-[20px]" v-for="item in amountConfig" :key="item.label">
            <span class="">{{ item.label }}：</span>
            <span class="font-[600]">
              {{ formModel.base.original_order_currency }}
              {{ (item.key && formModel[item.key] ? formModel[item.key][item.field] : String(formModel.base[item.field])) || "-" }}</span
            >
          </div>
        </template>

        <vxe-table ref="tableRef" class="mt-[9px]" :max-height="500" :column-config="{ resizable: true }" :row-config="{ isHover: true }" :data="formModel.products" round>
          <vxe-column title="编号" field="order_item_id" width="150"> </vxe-column>
          <vxe-column title="产品图片" field="product_main_img" width="80">
            <template #default="{ row }">
              <div>
                <VImage :width="58" :height="58" :src="row.main_img"></VImage>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="SKU/自定义SKU" width="200">
            <template #default="{ row }">
              <div>{{ row.sku }}</div>
              <div>{{ row.custom_sku }}</div>
            </template>
          </vxe-column>

          <vxe-column title="渠道SKU/ASIN" width="200">
            <template #default="{ row }">
              <div>{{ row.platform_sku }}</div>
              <div>{{ row.asin }}</div>
            </template>
          </vxe-column>
          <vxe-column title="平台链接规格" minWidth="140" v-if="formModel.products.find((v) => v.ebay_variation_aspects.length)">
            <template #default="{ row }">
              <div v-for="item in row?.ebay_variation_aspects" :key="item.value">
                <VText title="规格" :value="item.name" :line="1" />
                <VText title="参数" :value="item.value" :line="1" />
              </div>
            </template>
          </vxe-column>
          <vxe-column title="产品名称" field="sku_cn_title" width="200">
            <template #default="{ row }">
              <VText :value="row.sku_cn_title" :line="3" />
            </template>
          </vxe-column>
          <vxe-column title="物流属性" field="shipping_logistics_attr"> </vxe-column>
          <vxe-column title="产品数量" field="quantity"> </vxe-column>
          <vxe-column title="产品单价" field="original_price"> </vxe-column>
          <vxe-column title="产品总价" field="original_amount"> </vxe-column>
          <vxe-column title="可用库存" field="available_stock"> </vxe-column>
          <!-- <vxe-column title="锁定库存" field="lock_stock"> </vxe-column> -->
          <vxe-column title="采购单价/RMB" field="average_purchase_price" width="120"> </vxe-column>
        </vxe-table>
      </Card>
      <Card title="客户信息" class="pb-[4px] pr-[300px] v-anchor">
        <div class="flex flex-wrap">
          <Descriptions
            label-width="118px"
            v-for="item in clientInfo"
            :key="item.label"
            :label="item.label"
            :style="{ width: item.full ? '100%' : 'auto' }"
            :value="item.field === 'recipient_preferred_address' ? undefined : formModel['recipient'][item.field] + ' ' + (formModel['recipient'][item.field2] || '') || '-'"
          >
            <template v-if="item.field === 'recipient_preferred_address'" #value>
              <a class="text-[#3366F1]" @click="openMaps">{{ formModel["recipient"][item.field] }}</a>
            </template>
          </Descriptions>
        </div>
      </Card>
      <Card title="备注信息" class="pb-[4px] v-anchor">
        <div class="flex text-[14px] my-[12px]" v-if="formModel.base?.order_comment?.length">
          <div class="text-[#9da1ad] w-[98px] text-right">买家评价：</div>
          <div class="flex-1">
            <span v-for="(item, i) in formModel.base?.order_comment" :key="i" class="mr-[6px]">
              <span :class="commentColor[item.comment_type]"> {{ item.comment_type_desc }} </span>
              <span v-if="i != formModel.base.order_comment.length - 1">/</span>
            </span>
          </div>
        </div>

        <div class="flex flex-wrap">
          <Descriptions v-for="item in remarkInfo" :key="item.label" :label="item.label" :style="{ width: '100%' }" :value="formModel['base'][item.field] || '-'"> </Descriptions>
        </div>
      </Card>

      <Card title="附件信息" class="pb-[4px] v-anchor">
        <div v-for="(item, idx) in formModel?.base?.attachment" :key="idx" class="flex items-center my-[12px]">
          <label>文件类型：</label>
          <span> {{ item.type }}单 </span>
          <span class="mx-[8px]">{{ item.name }}</span>
          <el-link type="primary" :underline="false" class="mr-[12px]" @click="downloadRow(item.name)">下载</el-link>
        </div>
      </Card>
    </div>
    <div class="side-navigation">
      <div class="navigation">
        <div class="broadside">
          <div :class="['broadside-item cursor-pointer', index == sideActive ? 'active' : '']" v-for="(item, index) in sideNavigationData" :key="index" @click="scrollTop(index)">{{ item.label }}</div>
        </div>
        <div>
          <div :class="`mt-3 roll ${sideActive < 1 ? 'icon-atv' : ''}`" @click="toTop">
            <span :class="`dk-iconfont icon-top`"></span>
            <!-- <svg-icon class="text-[var(--base-color)] text-3xl" :icon-class="sideActive < 1 ? 'top' : 'top_on'"></svg-icon> -->
          </div>
          <div :class="`mt-3 roll ${sideActive >= 5 ? 'icon-atv' : ''}`" @click="toDown">
            <span :class="`dk-iconfont icon-down `"></span>
            <!-- <svg-icon class="text-[var(--base-color)] text-3xl" :icon-class="sideActive >= 5 ? 'down' : 'down_on'"></svg-icon> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus"
import Descriptions from "@/components/Descriptions/index.vue"
import VImage from "@/components/Image/index.vue"
import api from "@/views/user/list/add/api/index"
import Card from "../components/Card/index.vue"
import action from "@/utils/action.js"

import { isPermission } from "@/hooks/permission.js"
import { userAuthList } from "@/Auth/user.js"

import { importFilepath } from "../api"
const downloadRow = (name) => {
  importFilepath({ filepath: `attachment/${name}` }).then((res) => {
    if (res.data.url) {
      window.open(res.data.url, "noopener", "noreferrer")
    }
  })
}
import { nextTick } from "vue"
const props = defineProps({
  formModel: {
    type: Object,
    default: () => {},
  },
})
// 买家评价 字体颜色
const commentColor = {
  Positive: "text-green",
  Neutral: "text-blue",
  Negative: "text-red",
}
const data = reactive({
  scrollNode: "",
  scrollNodeY: "",
  parentNode: "",
  sideActive: 0,
  anchorsList: [],
  countryOptions: [],
})
const { scrollNode, scrollNodeY, parentNode, sideActive, anchorsList, countryOptions } = toRefs(data)

const sideNavigationData = ref([{ label: "基础信息" }, { label: "物流信息" }, { label: "支付信息" }, { label: "商品信息" }, { label: "客户信息" }, { label: "备注信息" }])

const handleScroll = () => {
  sideActive.value = anchorsList.value.findIndex((d) => d.getBoundingClientRect().y > scrollNodeY.value)
}
const toDown = () => {
  scrollTop(5)
}
//滚动到顶部
const toTop = () => {
  scrollTop(0)
}
const router = useRouter()

const Vpage = ref()
onMounted(() => {
  nextTick(() => {
    Vpage.value = document.querySelectorAll(".page-wrap")[0]
    Vpage.value.addEventListener("scroll", handleScroll)
    scrollNodeY.value = Vpage.value.getBoundingClientRect().y - 1
    parentNode.value = document.getElementById("anchors")
    update()
  })
})

// onBeforeUnmount(() => {
//   Vpage.value.removeEventListener("scroll", handleScroll)
// })
import keepAliveStore from "@/store/modules/keepalive"
const keepStore = keepAliveStore()
const routerName = router.currentRoute.value.name
watch(
  () => keepStore.currentKeepAliveList,
  (val) => {
    if (!val.includes(routerName)) {
      Vpage.value.removeEventListener("scroll", handleScroll)
    }
  }
)

const update = () => {
  nextTick(() => {
    if (!Vpage.value) return
    anchorsList.value = Array.from(Vpage.value.querySelectorAll(".v-anchor"))
    handleScroll()
  })
}
const scrollTop = (index) => {
  nextTick(() => {
    let anchorElement = document.querySelectorAll(".v-anchor")[index]
    let offsetTop = anchorElement.offsetTop - 40
    Vpage.value.scrollTo({ top: offsetTop, behavior: "smooth" })
  })
}

// 商品 支付信息
const amountConfig = [
  { label: "支付金额", field: "original_order_amount" },
  { label: "产品总价", field: "order_amount" },
  { label: "运费收入", field: "shipping_revenue" },
  { label: "优惠金额", field: "discount_amount" },
  { label: "其他收入", field: "other_price" },
  { label: "税费收入", field: "tax_amount" },
]

const stepsActive = computed(() => {
  return +props.formModel["base"].order_status
})

const steps = ref([
  { label: "待确认", value: 0 },
  { label: "已确认", value: 1 },
  { label: "问题单", value: 2 },
  // { label: '取消订单', value: 9 },
  { label: "采购缺货", value: 3 },
  { label: "待发货", value: 4 },
  { label: "已发货", value: 5 },
  { label: "派送在途", value: 6 },
  { label: "签收", value: 7 },
  { label: "拒收", value: 8 },
])

const baseInfo = [
  { label: "系统单号", field: "order_sn" },
  { label: "订单状态", field: "order_status_desc", light: true },
  { label: "订单类型", field: "order_type_desc" },
  { label: "来源平台", field: "platform" },
  { label: "国家/站点", field: "site" },
  { label: "店铺", field: "shop" },
  { label: "平台订单号", field: "platform_order_sn" },
  { label: "标发状态", field: "mark_shipment_status_desc" },
  { label: "拉单时间", field: "create_time" },
  { label: "下单时间", field: "order_time" },
  { label: "付款时间", field: "pay_time" },
  { label: "修改时间", field: "update_time" },
  { label: "发货时间", field: "shipping_time" },
  { label: "剩余发货时间", field: "latest_delivery_time", light: true },
  { label: "订单优先级", field: "priority" },
  { label: "平台运输方式", field: "platform_shipping_method" },
  { label: "订单发货类型", field: "shipping_type_desc" },
  { label: "新建订单原因", field: "new_order_reason_desc" },
  { label: "异常信息", field: "problem_cause", light: true, checkShow: true },
]
const gotuPage = () => {
  window.open("https://t.17track.net/zh-cn#nums=" + props.formModel["logistics"]?.platform_tracking_number)
}
const logisticsInfo = [
  { label: "发货仓库", field: "ship_warehouse_name", light: true },
  // { label: '发货运输方式', field: 'shipping_method_id', light: true },
  { label: "发货运输方式", field: "shipping_method", light: true },
  { label: "包裹单号", field: "parcel_no" },
  { label: "物流商单号", field: "logistics_bill_num" },
  { label: "物流商转单号", field: "logistics_transfer_num" },
  { label: "真实追踪号", field: "real_track_no" },
  { label: "标记追踪号", field: "tracking_number" },
  { label: "是否挂号", field: "registered" },
  { label: "商品数量", field: "quantity" },
  { label: "预估重量", field: "estimated_weight", unit: "g" },
  { label: "体积", field: "volume", unit: "cm³" },
  { label: "抛率", field: "throw_rate" },
  { label: "出库重量", field: "weight" },
  { label: "物流对账重量", field: "check_weight" },
  { label: "预估运费", field: "estimated_freight" },
  { label: "关税", field: "tariff" },
  { label: "实际运费", field: "freight" },
  { label: "对账状态", field: "bill_status_desc" },
  { label: "物流商(平台发货)", field: "platform_carrier", isFba: true },
  { label: "运单号(平台发货)", field: "platform_tracking_number", isFba: true, onClick: gotuPage },
]
const paymentInfo = [
  { label: "付款状态", field: "pay_status_desc" },
  { label: "订单支付金额", field: "original_order_amount", currency: true },
  { label: "已收金额", field: "original_order_amount", currency: true },
  { label: "付款时间", field: "pay_time" },
  { label: "付款类型", field: "payment_type_desc" },
  { label: "支付方式", field: "payment_mode_desc" },
  { label: "付款人", field: "recipient_name" },
  { label: "交易号", field: "transaction_no" },
  { label: "结算状态", field: "settlement_status_desc" },
]

const openMaps = () => {
  let param = "https://www.google.com/maps?daddr="
  let keys = ["recipient_country", "recipient_province", "recipient_city", "recipient_region", "recipient_preferred_address", "recipient_secondary_address"]
  keys.forEach((key) => {
    param += props.formModel.recipient[key] + " "
  })
  window.open(param, "_blank")
}

// 客户信息
const clientInfo = [
  { label: "买家ID", field: "clientele_id" },
  { label: "买家姓名", field: "buyer_name" },
  { label: "公司名", field: "recipient_company" },
  { label: "收件人", field: "recipient_name", field2: "recipient_last_name" },
  { label: "联系电话", field: "recipient_phone" },
  { label: "邮箱", field: "recipient_email" },
  { label: "收件人证件/税号", field: "recipient_tax_id" },
  { label: "国家/地区", field: "recipient_country" },
  { label: "州/省", field: "recipient_province" },
  { label: "城市", field: "recipient_city" },
  { label: "区/县", field: "recipient_region" },
  { label: "邮编", field: "recipient_zip_code" },
  { label: "门牌号", field: "recipient_door_num" },
  { label: "详细地址1", field: "recipient_preferred_address", full: true, slot: true },
  { label: "详细地址2", field: "recipient_secondary_address", full: true },
]
// 备注信息
const remarkInfo = [
  { label: "买家留言", field: "buyer_remark" },
  { label: "订单备注", field: "order_remark" },
  { label: "订单发货备注", field: "shipping_remark" },
  { label: "客服备注", field: "customer_service_remark" },
  { label: "物流备注", field: "logistics_remark" },
]
// 申请退款
const gotoRefundRecord = () => {
  router.push({
    path: "/user/refund",
    query: { form: "order", id: props.formModel.base.order_sn },
  })
}
// 申请退换货
const gotoRefundReturn = () => {
  if (props.formModel.base.order_status != 5) {
    return ElMessage.warning("订单状态不为‘已发货’，不可申请退换货")
  }
  router.push({
    path: "/user/return",
    query: { form: "order", id: props.formModel.base.order_sn },
  })
}
// 编辑订单
const handleEdit = () => {
  const { id } = props.formModel.base
  if (!id) return
  let view = router.currentRoute.value
  view.matched = []
  view = JSON.parse(JSON.stringify(view))
  view.path = "/oms" + view.path
  let backPath = router.options.history.base + router.options.history.state.back.replace("/oms", "")
  router.replace(`/user/list/addUpdata?id=${id}&type=edit`)
  setTimeout(() => {
    action.setGlobalState({
      changeMicoTabsPath: {
        type: "closeOtherTab",
        viewPath: view.path,
        backPath,
      },
    })
  }, 500)
}
</script>

<style lang="scss" scoped>
.steps {
  display: flex;

  .item-box {
    .item {
      .view {
        display: flex;
        align-items: center;
      }
      .link {
        width: 158px;
        height: 6px;
        background: var(--base-table-hover-bg-color);
      }
      .link.atv {
        background: #3487ff;
        .dk-icon {
          position: relative;
          color: var(--base-color);
          top: -7px;
          font-size: 14px;
          height: 10px;
          width: 10px;
          margin-left: 33px;
        }
      }
      .label {
        font-size: 12px;
        font-weight: 400;
        color: var(--base-placeholder-text-color);
        line-height: 17px;
        margin-top: 16px;
        margin-left: -6px;
      }
    }
  }
}

.side-navigation {
  width: 200px;
  padding-left: 10px;
  border-radius: 5px;
  .navigation {
    position: sticky;
    top: 40px;
  }
  .broadside {
    width: 100%;
    padding: 8px;
    padding-top: 24px;
    margin-right: 8px;
    background-color: var(--base-color);
    font-size: 14px;
  }
  .broadside-item {
    padding: 0 10px 28px 14px;
    // height: 8px;
    line-height: 30px;
    padding-left: 28px;
    position: relative;
    color: var(--base-placeholder-text-color);
    &::before {
      content: "";
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      border: 3px solid var(--base-border-color);
      background-color: var(--base-color);
      position: absolute;
      left: 1px;
      top: 9px;
      z-index: 9;
    }
    &::after {
      content: "";
      display: inline-block;
      width: 0px;
      height: 56px;
      border-left: 2px solid var(--base-border-color);
      position: absolute;
      left: 6px;
      top: 12px;
    }
    &:nth-last-child(1)::after {
      content: "";
      display: inline-block;
      width: 0px;
      height: 50px;
      border-left: 0px solid #e6e7e9;
      position: absolute;
      left: 3px;
      top: 12px;
    }
  }
  .broadside-item.active {
    color: #3487ff;
    &::before {
      border: 3px solid #3366f1;
    }
  }

  .roll {
    height: 32px;
    width: 32px;
    text-align: center;
    line-height: 32px;
    // border-right: pink;
    border-radius: 4px;
    background: var(--base-icon-color);
    &.icon-atv {
      background: var(--el-fill-color-light);
    }
    .dk-iconfont {
      font-size: 16px !important;
      color: var(--base-color);
    }
    // color: red;
    // &.active {
    //   background: red;
    // }
  }
}
.link {
  :deep(.value) {
    cursor: pointer !important;
    color: #3487ff !important;
  }
}
</style>
